package com.anssy.voteballot.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Path;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.anssy.voteballot.MainActivity;
import com.anssy.voteballot.R;
import com.anssy.voteballot.base.BaseActivity;
import com.anssy.voteballot.bean.OptionsRes;
import com.anssy.voteballot.bean.base.BaseRes;
import com.anssy.voteballot.constant.ConstantValue;
import com.anssy.voteballot.http.Api;
import com.anssy.voteballot.http.HttpService;
import com.anssy.voteballot.utils.CurrencyUtils;
import com.anssy.voteballot.utils.DeviceUtils;
import com.anssy.voteballot.utils.HttpUtils;
import com.anssy.voteballot.utils.VersionUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AnswerOneActivity extends BaseActivity implements View.OnClickListener {


    private RecyclerView mRecyclerView;
    private TextView mTvSubjectName;
    private TextView mTvCountdown;
    private TextView mTvSecondTitle;
    private TextView mTvTitle;
    private Button mBtnSubmit;
    private OptionsRes optionsRes;
    private List<OptionsRes.DatasBeans.ListOPSBeans> listOPS;
    private int selectId;
    private int meettingSubId;
    private TimeCount time;
    private TextView mTvDeviceId;
    private TextView mTvVersion;
    private TextView mTvNetStatus;


    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public int setLayoutResource() {
        return R.layout.activity_answer_one;
    }

    @Override
    public void initView() {
        mTvTitle = findViewById(R.id.tv_title);
        mTvSecondTitle = findViewById(R.id.tv_second_title);
        mTvSubjectName = findViewById(R.id.tv_subject_name);
        mTvCountdown = findViewById(R.id.tv_countdown);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mRecyclerView = findViewById(R.id.rv_option_type_one);
        mTvDeviceId = findViewById(R.id.tv_device_id);
        mTvVersion = findViewById(R.id.tv_version_code);
        mTvNetStatus = findViewById(R.id.tv_net_status);
    }

    @Override
    public void initData() {
        getDataFromServer();
        setBottomData();
    }

    @SuppressLint("SetTextI18n")
    private void setBottomData() {
        CurrencyUtils.checkNetStatus(mTvNetStatus);
        if (!TextUtils.isEmpty(VersionUtils.getVersion(AnswerOneActivity.this))) {
            mTvVersion.setText("版本号:v" + VersionUtils.getVersion(AnswerOneActivity.this));
        }
        mTvDeviceId.setText("设备ID:" + DeviceUtils.getUniqueId(AnswerOneActivity.this));
    }

    private void getDataFromServer() {
        Api.getRetrofit().create(HttpService.class).getOptions(getIntent().getIntExtra(ConstantValue.ID, 0), DeviceUtils.getUniqueId(this))
                .enqueue(new Callback<ResponseBody>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        optionsRes = (OptionsRes) HttpUtils.parseResponse(response, OptionsRes.class);
                        if (optionsRes != null && optionsRes.getCode() == 200) {
                            time = new TimeCount(optionsRes.getDatas().getTimeOutSet() * 1000L, 1000);
                            time.start();
                            mTvCountdown.setText("倒计时: " + optionsRes.getDatas().getTimeOutSet());
                            if (!TextUtils.isEmpty(optionsRes.getDatas().getMeettingTitel())) {
                                mTvTitle.setText(optionsRes.getDatas().getMeettingTitel());
                            }
                            if (!TextUtils.isEmpty(optionsRes.getDatas().getMeettingFuTitel())) {
                                mTvSecondTitle.setText("———" + optionsRes.getDatas().getMeettingFuTitel());
                            }
                            if (!TextUtils.isEmpty(optionsRes.getDatas().getTitle())) {
                                mTvSubjectName.setText("议题: " + optionsRes.getDatas().getTitle());
                            }
                            listOPS = optionsRes.getDatas().getListOPS();
                            mRecyclerView.setLayoutManager(new GridLayoutManager(AnswerOneActivity.this, 3, LinearLayoutManager.VERTICAL, false));
                            mRecyclerView.setAdapter(new MyAdapter(AnswerOneActivity.this, listOPS));
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        private final Context context;
        private final List<OptionsRes.DatasBeans.ListOPSBeans> dataBeansList;

        public MyAdapter(Context context, List<OptionsRes.DatasBeans.ListOPSBeans> dataBeansList) {
            this.context = context;
            this.dataBeansList = dataBeansList;
        }

        @NonNull
        @Override
        public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_rv_type_one, parent, false);
            return new MyViewHolder(view);

        }

        @SuppressLint("UseCompatLoadingForDrawables")
        @Override
        public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
            if (dataBeansList.get(position).isSelect()) {
                holder.mBtnText.setBackground(getResources().getDrawable(R.drawable.bg_circle));
            } else {
                holder.mBtnText.setBackground(getResources().getDrawable(R.drawable.bg_circle_default));
            }
            if (!TextUtils.isEmpty(dataBeansList.get(position).getOptionContent())) {
                holder.mBtnText.setText(dataBeansList.get(position).getOptionContent());
            } else {
                holder.mBtnText.setText("");
            }
            holder.mBtnText.setOnClickListener(new View.OnClickListener() {
                @SuppressLint({"UseCompatLoadingForDrawables", "NotifyDataSetChanged"})
                @Override
                public void onClick(View view) {
                    for (int i = 0; i < dataBeansList.size(); i++) {
                        if (position == i) {
                            dataBeansList.get(i).setSelect(true);

                        } else {
                            dataBeansList.get(i).setSelect(false);
                        }
                    }
                    notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataBeansList.size();
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {

            private final Button mBtnText;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                mBtnText = itemView.findViewById(R.id.btn_type_one);
            }
        }
    }

    @Override
    public void initListener() {
        mBtnSubmit.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_submit:
                submitScore(1);
                break;

            default:
                break;
        }
    }

    //flag 0 倒计时结束提交 1 按钮提交
    private void submitScore(int flag) {
        if (listOPS != null && listOPS.size() > 0) {
            for (int i = 0; i < listOPS.size(); i++) {
                if (listOPS.get(i).isSelect()) {
                    selectId = listOPS.get(i).getId();
                    meettingSubId = listOPS.get(i).getMeettingSubId();
                }
            }
            if (selectId == 0 || meettingSubId == 0) {
                if (flag == 0) {
                    finish();
                } else {
                    ToastUtils.showShort("请选择之后进行提交");
                }
            }
            Api.getRetrofit().create(HttpService.class).submitVote(DeviceUtils.getUniqueId(AnswerOneActivity.this), meettingSubId, String.valueOf(selectId))
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                            BaseRes baseRes = HttpUtils.parseResponse(response, BaseRes.class);
                            if (baseRes != null) {
                                if (baseRes.getCode() == 200) {
                                    ToastUtils.showShort("投票成功");
                                } else {
                                    ToastUtils.showShort(baseRes.getMsg());
                                }
                                finish();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            t.printStackTrace();
                        }
                    });
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
//            LogUtils.v(TAG, millisUntilFinished);
            long readTime = millisUntilFinished / 1000;
            mBtnSubmit.setClickable(true);
            if (readTime >= 0) {
                mTvCountdown.setText("倒计时: " + readTime);
            }
        }

        @Override
        public void onFinish() {
            mBtnSubmit.setClickable(false);
            submitScore(0);
        }
    }

}
